package com.kaifamiao.uploader.controller;

import com.kaifamiao.uploader.entity.Chunk;
import com.kaifamiao.uploader.entity.Resp;
import com.kaifamiao.uploader.service.ChunkService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.annotation.MultipartConfig;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/chunk")
@MultipartConfig(maxFileSize = -1L, maxRequestSize = -1L)
@Slf4j
public class ChunkController {

    @Autowired
    private ChunkService chunkService;

    @GetMapping("/check")
    public Resp checkChunk(Chunk chunk) {
        log.info("chunk: {}", chunk);
        List<Chunk> chunks = chunkService.findChunksByFileIdentifier(chunk.getIdentifier());
        return Resp.success(chunks);
    }

    @PostMapping("/upload")
    public Resp upload(Chunk chunk, MultipartFile file) {
        log.info("chunk: {}", chunk);

        log.debug("file originName: {}, chunkIndex: {}", file.getOriginalFilename(), chunk.getChunkIndex());

        try {
            //文件写入指定路径
            chunkService.uplaod(chunk, file);
            return Resp.success("分片上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            return Resp.error("分片上传失败");
        }
    }


    @GetMapping("/merge")
    public Resp merge(String iderntifier) throws IOException {
        log.info("iderntifier: {}", iderntifier);
        String path = chunkService.merge(iderntifier);
        return Resp.success().put("data", path);
    }
}
